<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addList="addList" />
    <!-- 主体部分 -->
    <TodoBody
      :list="renderlist"
      @delList="delList"
      @changStaues="changStaues"
      :isCheckAll="isCheckAll"
      @changeChecked="changeChecked"
    />
    <!-- 底部部分 -->
    <TodoFooter
      :type="type"
      :left="left"
      :isDoneAll="isDoneAll"
      @clear="clear"
      @changeType="changeType"
      v-show="list.length"
    />
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoBody from '@/components/TodoBody.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoBody,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('TodoList')) || [],
      type: 'all',
    }
  },
  methods: {
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    changStaues(id) {
      const res = this.list.find((item) => item.id === id)
      res.isDone = !res.isDone
    },
    addList(value) {
      const obj = { id: +new Date(), name: value, isDone: false }
      this.list = [obj, ...this.list]
    },
    clear() {
      this.list = this.list.filter((item) => item.isDone === false)
    },
    changeType(type) {
      this.type = type
    },
    changeChecked(flag) {
      this.list.forEach((item) => (item.isDone = flag))
    },
  },
  computed: {
    left() {
      return this.list.filter((item) => item.isDone === false).length
    },
    isDoneAll() {
      return this.list.some((item) => item.isDone)
    },
    renderlist() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.isDone)
        case 'completed':
          return this.list.filter((item) => item.isDone)
        default:
          return this.list
      }
    },
    isCheckAll() {
      return this.list.every((item) => item.isDone)
    },
  },

  watch: {
    list: {
      immediate: true,
      deep: true,
      handler(value) {
        localStorage.setItem('TodoList', JSON.stringify(value))
      },
    },
  },
}
</script>

<style></style>
